<?php
namespace app\api\library;

use think\Cache;
use fast\Http;

class WechatPhone {
    // 小程序appid
    private $appid;
    // 小程序secret
    private $secret;
    
    public function __construct($appid, $secret) {
        $this->appid = $appid;
        $this->secret = $secret;
    }
    
    /**
     * 获取微信接口调用凭证
     * @return string|bool 成功返回access_token，失败返回false
     */
    public function getAccessToken() {
        $cacheKey = "wechat_access_token_{$this->appid}";
        
        // 尝试从缓存中获取access_token
        $accessToken = Cache::get($cacheKey);

        if ($accessToken) {
            return $accessToken;
        }

        $url = "https://api.weixin.qq.com/cgi-bin/stable_token";
        
        $result = Http::post($url,[
            'grant_type' => 'client_credential',
            'appid' => $this->appid,
            'secret' => $this->secret
        ]);

        $result = json_decode($result, true);
        
        if (isset($result['access_token'])) {
            Cache::set($cacheKey, $result['access_token'], 7000);
            return $result['access_token'];
        }
        
        // 记录错误日志
        $this->logError("获取access_token失败: " . json_encode($result));
        return false;
    }

    public function getOpenId($code) {
        $access_token = $this->getAccessToken();
        if (!$access_token) {
            return false;
        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appid}&secret={$this->secret}&js_code={$code}&grant_type=authorization_code";
        $result = Http::get($url);
        $result = json_decode($result, true);

        if ($result['openid']) {
            return $result;
        }

        // 错误处理
        $this->logError("openid获取失败: " . json_encode($result));
        return false;
    }
    
    /**
     * 解密用户手机号
     * @param string $encryptedData 加密的手机号数据
     * @param string $iv 加密向量
     * @param string $sessionKey 会话密钥
     * @return array|bool 成功返回手机号信息数组，失败返回false
     */
    public function decryptPhone($code,$access_token) {
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$access_token}";
        $result = Http::post($url, ['code' => $code]);
        
        $result = json_decode($result, true);
        
        if (isset($result['phone_info'])) {
            return $result['phone_info'];
        }
        
        // 错误处理
        $this->logError("解密手机号失败: " . json_encode($result));
        return false;
    }
    
    
    /**
     * 记录错误日志
     * @param string $message 错误信息
     */
    private function logError($message) {
        $time = date('Y-m-d H:i:s');
        $logContent = "[{$time}] Error: {$message}\n";
        \think\Log::write($logContent,'error');
    }
}

?>
